package base

import (
	"context"
	"rewords-server-2024/internal/consts"
	"rewords-server-2024/internal/library/ecode"
	"rewords-server-2024/internal/logic/mgx"
	"rewords-server-2024/internal/model/entity"
	"rewords-server-2024/internal/service"

	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"

	"rewords-server-2024/api/base/system"
)

func (c *ControllerSystem) SysUserAdd(ctx context.Context, req *system.SysUserAddReq) (res *system.SysUserAddRes, err error) {

	userDoc := &entity.SysUser{
		Username: req.Username,
		Email:    req.Email,
		Phone:    req.Phone,
		Openid:   req.Openid,
		Nickname: req.Nickname,
		Avatar:   req.Avatar,
		Level:    req.Level,
		Points:   req.Points,
		Role:     req.Role,
		Status:   req.Status,
		UnionId:  req.UnionId,
	}
	uid, err := mgx.GetAutoInc("user")
	if err != nil {
		// 处理错误，例如记录日志或返回错误信息
		g.Log().Printf(ctx, "Failed to get auto increment value for user: %v", err)
		// 根据实际情况决定如何处理错误，例如返回一个错误值或中断程序
		return nil, gerror.NewCode(ecode.InvalidParams)
	}
	userDoc.Uid = int64(uid)
	userDoc.SetTimeValue(0)
	userDoc.SetTimeValue(1)

	err = service.Mgx().InsertOne(ctx, consts.CUser, userDoc)
	//doc := form.NewBuilder().FromModel(userDoc).Build()
	if err != nil {
		g.Log().Error(ctx, "Insert error:", err)
		return nil, gerror.NewCode(ecode.InvalidParams)
	}

	return &system.SysUserAddRes{
		Uid: int64(uid),
	}, nil
}
